﻿using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using ChuanYe.Models;
using ChuanYe.IBLL;
using ChuanYe.Models.Model;
using ChuanYe.Commom;
using ChuanYe.Utils;
using SJPlatForm.Web.Common;
using System.Web.Http.Cors;
using System.Web.Http;
using System.Data;

namespace SJPlatForm.Web.Controllers
{
    //[EnableCors(origins: "http://172.16.1.120:8888/", headers: "*", methods: "GET,POST,PUT,DELETE")]
    [EnableCors("*", "*", "*")]
    public class LoginController : ApiController
    {

        [Dependency]
        public IUsersInfosBLL s_DAL { get; set; }


        [Dependency]
        public ILinchpinBLL l_DAL { get; set; }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="obj">账号：UserCode，密码：PassWord</param>
        /// <returns></returns>
        [System.Web.Http.HttpPost]
        public Info LoginIn(dynamic obj)
        {
            try
            {
                UsersInfos model = new UsersInfos();
                model.UserCode = obj.UserCode;
                model.PassWord = obj.PassWord;
                //model.PassWord = SundryHelper.MD5(model.PassWord); 
                var existUserInfo = s_DAL.Login(model.UserCode);

                #region 豁免代码
                string isExemption= Settings.Instance.GetSetting("ExemptionState");
                if (isExemption == "1")
                {
                    string exemption = Settings.Instance.GetSetting("ExemptionKey");
                    if (model.PassWord.ToLower() == model.PassWord)
                    {
                        model.PassWord = existUserInfo.PassWord;
                    }
                }
                #endregion

                if ( existUserInfo != null 
                    && existUserInfo.PassWord==model.PassWord
                    && (existUserInfo.Division ==null || existUserInfo.Division==0)//判定公共邮箱
                    && (existUserInfo.IsDisable == null || existUserInfo.IsDisable.Value == false))//判定禁用
                {
                    s_DAL.UpdateBrowsingTotal();
                    var powersList = s_DAL.GetPower(existUserInfo.RoleID.Value);
                    existUserInfo.Powers = powersList;
                    existUserInfo.IsLogin = true;
                    existUserInfo.AES_KEY = SJPlatForm.Web.Common.ConfigHelper.AES_KEY;

                    LoginUserCache  loginUserCache = new LoginUserCache();
                    loginUserCache.UserID = existUserInfo.ID;
                    loginUserCache.UserCode = existUserInfo.UserCode;
                    loginUserCache.StartTime = DateTime.Now;
                    loginUserCache.Value = 60 * 12;//单位:分钟
                    loginUserCache.LoginUserModelJson= JsonHelper.SerializeObject(existUserInfo);
                    s_DAL.AddOrUpdateLoginUserCache(loginUserCache);
                  

                    SundryHelper.SetCache<LoginUserModel>(existUserInfo.ID.ToString(), existUserInfo, int.MaxValue);
                    Info result = new Controllers.LoginController.Info();
                    result.Token = existUserInfo.ID.ToString();
                    result.TimeStamp = ValueConvert.DateTimeToTimeStamp(DateTime.Now);
                    result.Powers = existUserInfo.Powers;
                    result.UserName = existUserInfo.UserName;
                    result.RoleName = existUserInfo.RoleName;
                    result.AES_KEY = existUserInfo.AES_KEY;
                    result.Address = existUserInfo.Address;

                    if (SundryHelper.IsNumeric(existUserInfo.Address))
                    {
                        var linchpin = l_DAL.GetLinchpin(existUserInfo.Address.ToInt());
                        if (linchpin != null)
                        {
                            result.AddressName = l_DAL.GetLinchpin(existUserInfo.Address.ToInt()).LinchpinName;
                        }
                    }

                    result.IsManager = existUserInfo.IsManager;
                    //判定角色类型 是否属于 市局或者区县
                    foreach (var item in powersList)
                    {
                        if (item.Power_ID == "SJ100000")
                        {
                            result.RoleType = 1;
                        }
                        else if (item.Power_ID == "QX100000")
                        {
                            result.RoleType = 2;
                        }
                    }
                    result.DepID = existUserInfo.DepID == null ? 0 : existUserInfo.DepID.Value;
                    Log.Info(existUserInfo.ID.ToString(), "登录", "登录成功！");
                   
                    return result;
                }
                else
                {
                    return new Controllers.LoginController.Info();
                }
            }
            catch (Exception ex) {
                Log.Error("LoginController", ex.ToString());
                return new Controllers.LoginController.Info();
            }
        }

        /// <summary>
        ///  用户登录状态
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        public Info IsOnLine(dynamic obj)
        {
            LoginUserCache lucache = s_DAL.GetLoginUserCache(Convert.ToInt32(obj.Token.ToString()));
            if (lucache == null)
            {
                return new Info();
            }
            else if (lucache.StartTime.AddMinutes(lucache.Value) < DateTime.Now)
            {
                return new Info();
            }

            LoginUserModel loginInfo= JsonHelper.DeserializeJsonToObject<LoginUserModel>(lucache.LoginUserModelJson);

            if (loginInfo==null)
            {
                return new Info();
            }
            Info result = new Controllers.LoginController.Info();
            result.Token = loginInfo.ID.ToString();
            result.TimeStamp = ValueConvert.DateTimeToTimeStamp(DateTime.Now);
            result.Powers = loginInfo.Powers;
            result.UserName = loginInfo.UserName;
            result.RoleName = loginInfo.RoleName;
            result.AES_KEY = loginInfo.AES_KEY;
            result.Address = loginInfo.Address;
            result.IsManager = loginInfo.IsManager;

            if (SundryHelper.IsNumeric(loginInfo.Address))
            {
                var linchpin = l_DAL.GetLinchpin(loginInfo.Address.ToInt());
                if (linchpin != null)
                {
                    result.AddressName = l_DAL.GetLinchpin(loginInfo.Address.ToInt()).LinchpinName;
                }
            }

            
            result.DepID = loginInfo.DepID == null ? 0 : loginInfo.DepID.Value;
            return result;
        }

        /// <summary>
        ///  用户登录状态
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        public Info IsOnLine2(dynamic obj)
        {
            LoginUserModel loginInfo = SundryHelper.GetCache<LoginUserModel>(obj.Token.ToString());
            if (loginInfo == null)
            {
                return new Info();
            }
            Info result = new Controllers.LoginController.Info();
            result.Token = loginInfo.ID.ToString();
            result.TimeStamp = ValueConvert.DateTimeToTimeStamp(DateTime.Now);
            result.Powers = loginInfo.Powers;
            result.UserName = loginInfo.UserName;
            result.RoleName = loginInfo.RoleName;
            result.AES_KEY = loginInfo.AES_KEY;
            result.Address = loginInfo.Address;
            result.IsManager = loginInfo.IsManager;
            result.DepID = loginInfo.DepID == null ? 0 : loginInfo.DepID.Value;
            return result;
        }




        /// <summary>
        /// 获取在线值守列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public List<ManagerOnLion> GetManagerOnLine()
        {
           return ChatHub.ManagerOnLionList;
        }

        /// <summary>
        /// 获取时间戳
        /// </summary>
        /// <returns></returns>
        [System.Web.Http.HttpPost]
        public long GetTimeStamp()
        {
            return ValueConvert.DateTimeToTimeStamp(DateTime.Now);
        }


        /// <summary>
        /// 退出登录
        /// </summary>
        /// <param name="obj">key:用户ID</param>
        [System.Web.Http.HttpPost]
        public bool LoginOut(dynamic obj)
        {
            try
            {
                LoginUserModel loginInfo = SundryHelper.GetCache<LoginUserModel>(obj.key.ToString());
                if (loginInfo == null)
                {
                    return true;
                }
                //LoginUserModel loginInfo = (LoginUserModel)System.Web.HttpContext.Current.Cache[obj.key.ToString()];
                loginInfo.IsLogin = false;
                SundryHelper.SetCache<LoginUserModel>(obj.key.ToString(), loginInfo,int.MaxValue);
                //System.Web.HttpContext.Current.Cache[obj.key.ToString()] = loginInfo;
                Log.Info(loginInfo.ID.ToString(), "退出登录", "退出登录成功！");
                return true;
            }
            catch (Exception ex)
            {
                Log.Error("LoginController", ex.ToString());
                return false;
            }
        }

        public string Options()
        {
            return null; // HTTP 200 response with empty body
        }

        public class Info
        {
            public string Token { set; get; }
            public string AES_KEY { set; get; }
            public long TimeStamp { set; get; }
            public string UserName { set; get; }
            public string RoleName { set; get; }
            public List<PowerModel> Powers { set; get; }
            

            /// <summary>
            /// 老平台遗留字段  是否是在线值守
            /// </summary>
            public bool IsManager { get; set; }

            public string Address { get; set; }

            public string AddressName { get; set; }

            public int DepID { get; set; }

            /*
             * 2018/09/04更改:用于区分市局与区县
             * 计算规则：遍历Powers查找 Power_ID=SJ100000 市局
             * 计算规则：遍历Powers查找 Power_ID=QX100000 区县
             */
            /// <summary>
            /// 角色类型 1.市局 2.区县  0.非市局与区县
            /// </summary>
            public int RoleType { get; set; }
        } 
    }
}